import time
import inspect
from functools import wraps
import os
import json

trace_event = []

def _log_event(name, ph, ts, dur, args=None):
	event = {
		'name': name,
		'ph': ph,
		'ts': ts,  # Convert to microseconds
		'dur': dur,
		'pid': os.getpid(),  # Process ID
		'tid': os.getthreadid() if hasattr(os, 'getthreadid') else 0
	}
	if args is not None:
		event['args'] = args
	trace_event.append(event)

def save_to_file(filename='log.json'):
	with open(filename, 'w') as f:
		json.dump(trace_event, f, indent=2)

def trace_decorator(func):
    """
    这是一个装饰器，它会在被装饰的函数执行前后记录时间，并打印出函数名和文件名。
    :param func: 被装饰的函数
    :return: 装饰后的函数
    """
    def wrapper(*args, **kwargs):
        # 获取当前帧对象
        current_frame = inspect.currentframe()
        # 通过当前帧对象获取调用者的帧对象
        caller_frame = current_frame.f_back
        # 获取调用者的信息
        info = inspect.getframeinfo(caller_frame)
        
        # 记录开始时间
        start_time = int(round(time.time() * 1000_000))
        
        # 执行实际的函数
        result = func(*args, **kwargs)
        
        # 记录结束时间
        end_time = int(round(time.time() * 1000_000)) 
        
        frame = inspect.currentframe().f_back
        fname = inspect.getfile(frame.f_code)
        function_name = func.__name__
        _log_event(
                name=function_name,
                ph='X',  # Complete event
                ts=start_time,
                dur=(end_time - start_time),  # Duration in millisecon
                args={
                    'file': fname
                    }
                )

        return result
    
    return wrapper
